package com.diaohaiwen.basic.websockt;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.diaohaiwen.basic.websockt.obj.bo.FileBo;
import com.diaohaiwen.common.util.CryptoUtil;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;

/**
 * @author 刁海文
 * @since 2023/12/9 22:01
 */
public class StorageUtil {

    public final static String ROOT = "file";

    @SneakyThrows
    public static FileBo storage(MultipartFile file) {
        String folder = folder();

        String ext = FileUtil.extName(file.getOriginalFilename());

        String md5 = CryptoUtil.md5(file.getInputStream());

        String filename = md5 + "." + ext;

        FileUtil.writeFromStream(file.getInputStream(), new File(folder, filename));

        return new FileBo()
                .setFilename(filename)
                .setContentType(file.getContentType())
                .setLength(file.getSize())
                .setOriginal(file.getOriginalFilename())
                .setFolder(folder)
                .setMd5(md5);
    }


    public static String folder() {
        return ROOT + File.separator + DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN);
    }

}
